<template>
  <div class="profile-container">
    <el-card class="profile-card">
      <template #header>
        <div class="card-header">
          <span>个人信息</span>
          <el-button type="primary" @click="handleEdit" v-if="!isEditing">编辑</el-button>
        </div>
      </template>

      <el-form 
        ref="formRef"
        :model="form"
        :rules="rules"
        label-width="100px"
        :disabled="!isEditing"
      >
        <el-form-item label="用户名" prop="username">
          <el-input v-model="form.username" disabled />
        </el-form-item>

        <el-form-item label="姓名" prop="name">
          <el-input v-model="form.name" />
        </el-form-item>

        <el-form-item label="性别" prop="gender">
          <el-select v-model="form.gender" style="width: 100%">
            <el-option label="男" value="男" />
            <el-option label="女" value="女" />
          </el-select>
        </el-form-item>

        <el-form-item label="手机号" prop="phone">
          <el-input v-model="form.phone" />
        </el-form-item>

        <el-form-item label="积分">
          <el-input v-model="form.points" disabled />
        </el-form-item>

        <el-form-item v-if="isEditing">
          <el-button type="primary" @click="handleSave" :loading="loading">保存</el-button>
          <el-button @click="handleCancel">取消</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 我的订单 -->
    <el-card class="orders-card">
      <template #header>
        <div class="card-header">
          <span>最近订单</span>
          <router-link to="/user/orders" class="more-link">查看更多</router-link>
        </div>
      </template>

      <el-table :data="recentOrders" style="width: 100%">
        <el-table-column prop="id" label="订单编号" width="180" />
        <el-table-column prop="createTime" label="下单时间" width="180" />
        <el-table-column prop="total" label="金额">
          <template #default="{ row }">
            <span class="price">¥{{ row.total.toFixed(2) }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态">
          <template #default="{ row }">
            <el-tag :type="getStatusType(row.status)">{{ row.status }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="100">
          <template #default="{ row }">
            <router-link :to="`/user/orders?id=${row.id}`">查看详情</router-link>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { updateUser } from '../api'

const formRef = ref(null)
const isEditing = ref(false)
const loading = ref(false)
const recentOrders = ref([])

const form = reactive({
  username: '',
  name: '',
  gender: '',
  phone: '',
  points: 0
})

const rules = {
  name: [{ required: true, message: '请输入姓名', trigger: 'blur' }],
  gender: [{ required: true, message: '请选择性别', trigger: 'change' }],
  phone: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' }
  ]
}

const initForm = () => {
  const user = JSON.parse(localStorage.getItem('user') || '{}')
  Object.assign(form, user)
}

const handleEdit = () => {
  isEditing.value = true
}

const handleSave = async () => {
  if (!formRef.value) return
  
  try {
    await formRef.value.validate()
    loading.value = true
    const user = JSON.parse(localStorage.getItem('user') || '{}')
    await updateUser(user.id, form)
    localStorage.setItem('user', JSON.stringify({ ...user, ...form }))
    isEditing.value = false
    ElMessage.success('保存成功')
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('保存失败')
    }
  } finally {
    loading.value = false
  }
}

const handleCancel = () => {
  isEditing.value = false
  initForm()
}

const getStatusType = (status) => {
  const map = {
    '待付款': 'warning',
    '已付款': 'success',
    '已发货': 'primary',
    '已完成': 'success',
    '已取消': 'info'
  }
  return map[status] || 'info'
}

// 加载最近订单
const loadRecentOrders = async () => {
  try {
    const user = JSON.parse(localStorage.getItem('user') || '{}')
    // 这里需要调用获取订单的API，并限制只获取最近的几条
    // const { data } = await getOrders(user.id, { limit: 5 })
    // recentOrders.value = data
  } catch (error) {
    ElMessage.error('获取订单失败')
  }
}

onMounted(() => {
  initForm()
  loadRecentOrders()
})
</script>

<style scoped>
.profile-container {
  display: grid;
  gap: 20px;
  grid-template-columns: 1fr 1fr;
}

.profile-card {
  height: fit-content;
}

.orders-card {
  height: fit-content;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.more-link {
  font-size: 14px;
  color: #409EFF;
  text-decoration: none;
}

.more-link:hover {
  text-decoration: underline;
}

.price {
  color: #f56c6c;
  font-weight: bold;
}

@media (max-width: 768px) {
  .profile-container {
    grid-template-columns: 1fr;
  }
}
</style> 